import web3 from '../util/web3utils';
import {fundingFactoryContract,NewCrowFundingContract} from '../api/deploy';

//index = 1， 代表第一个页面，获取所有all的合约
//index = 2， 代表第二个页面，获取Sponsor的合约
//index = 3， 代表第三个页面，获取support的合约
let getFundingDetailArrayByTabId = (index) => {
    return new Promise(async (resolve, reject) => {
        try {
            let accounts =await web3.eth.getAccounts();
            console.log(accounts[0]);
            let fundings = [];
            if (index === 1) {
                fundings = await fundingFactoryContract.methods.getAllFundings().call({
                    from: accounts[0]
                })

            } else if (index === 2) {
                //得到发起人的所有众筹合约

                fundings = await await fundingFactoryContract.methods.getSingleCrowFundingArray().call({
                    from: accounts[0]
                })


            } else if (index === 3) {
                fundings = await fundingFactoryContract.methods.getSupporterFundings().call({
                    from: accounts[0]
                })

            } else {
                reject("输入错误")
            }




            //let fundingDetails = [] //所有合约的详细信息的集合，遍历
            let fundingDetailsPromiseArray = fundings.map(funding => getFundingDetail(funding));
            //将所有的Promise转成一个Promise
            let fundingDetailsArray = Promise.all(fundingDetailsPromiseArray);

            resolve(fundingDetailsArray);
        } catch (e) {
            reject(e);
        }
    })
};
let getFundingDetail= (fundingAddress) => {
    return new Promise(async (resolve, reject) => {
        //众筹合约的地址
        //这个fundingContract已经完整，可以调用了
        try {
            let fundingContractInstance=NewCrowFundingContract();
            fundingContractInstance.options.address = fundingAddress;

            let accounts = await web3.eth.getAccounts();
            //根据合约的实例，获取这个合约的详细信息
            //let manager = await fundingContractInstance.methods.creator().call({from: accounts[0]});
            let projectName = await fundingContractInstance.methods.projectName().call({from: accounts[0]});
            let supportMoney = await fundingContractInstance.methods.supportMoney().call({from: accounts[0]});
            let targetMoney = await fundingContractInstance.methods.targetMoney().call({from: accounts[0]});
            let balance = await fundingContractInstance.methods.getBalance().call({from: accounts[0]});
            let supporters = await fundingContractInstance.methods.getSupporters().call({from: accounts[0]});
            let leftTime = await fundingContractInstance.methods.getLeftTime().call({from: accounts[0]});
            let supportersCount = await fundingContractInstance.methods.getSupportersCount().call({from: accounts[0]});

            // console.log('111111 manager :', manager)
            resolve([fundingAddress, projectName, supportMoney, targetMoney, balance, supporters,leftTime,supportersCount])
            // console.table(fundingDetails)
        } catch (e) {
            reject(e)
        }
    })
}


const createFunding = (projectName, supportMoney, targetMoney, durationTime) => {
    return new Promise(async (resolve, reject) => {
        try {
            let accounts = await web3.eth.getAccounts();
            let result = await fundingFactoryContract.methods.createFunding(projectName, supportMoney, targetMoney, durationTime).send({
                from: accounts[0]
            });
            console.log("result:",result);
            resolve(result);
        } catch (e) {
            reject(e);
        }
    })
}

const supportFunding = (funding, supportMoney) => {
    return new Promise(async (resolve, reject) => {
        try {
            let accounts = await web3.eth.getAccounts();
            //创建新的合约实例，将点击的众筹项目地址传递进去，然后才能发起参与
            let fundingContract = NewCrowFundingContract();
            fundingContract.options.address = funding;
            let result = await fundingContract.methods.support().send({
                from: accounts[0],
                //参与要传递相应的金额
                value: supportMoney,
            });
            resolve(result);
        } catch (e) {
            reject(e);
        }
    })
};
const createRequest = (fundingAddress, purpose, cost, seller) => {
    return new Promise(async (resolve, reject) => {
        try {
            let accounts = await web3.eth.getAccounts();
            let fundingContract = NewCrowFundingContract();
            fundingContract.options.address = fundingAddress;
            let result = await fundingContract.methods.createRequest(purpose, seller, cost).send({
                from: accounts[0],
            });
            console.log(result)
            resolve(result);
        } catch (e) {
            reject(e);
        }
    })
};
//返回所有请求
const getAllRequests = (fundingAddress) => {
    return new Promise(async (resolve, reject) => {
        try {
            let accounts = await web3.eth.getAccounts();
            let fundingContract = NewCrowFundingContract();
            fundingContract.options.address = fundingAddress;
            //拿到请求的数量: 3
            let requestCount = await fundingContract.methods.getRequestCount().call({
                from: accounts[0],
            });

            let requestDetails = [];
            for (let i = 0; i < requestCount; i++) {
                let requestDetail = await fundingContract.methods.getRequestByIndex(i).call({
                    from: accounts[0],
                });

                requestDetails.push(requestDetail);
            }
            resolve(requestDetails);
        } catch (e) {
            reject(e);
        }
    })
};
//同意请求花费
const approveRequest = (address, index) => {
    return new Promise(async (resolve, reject) => {
        try {
            const accounts = await web3.eth.getAccounts();
            const account = accounts[0];
          /*  console.log(`account: ${account}`);
            console.log(`funding: ${address}`);
            console.log(`index: ${index}`);*/
            const contract = NewCrowFundingContract();
            contract.options.address = address;
            const result = await contract.methods.approveRequest(index).send({
                from: account,
            });
            console.log('result :', result);

            resolve(result);
        } catch (e) {
            reject(e);
        }
    })
};
const finalizeRequest = (address, index) => {
    return new Promise(async (resolve, reject) => {
        try {
            const accounts = await web3.eth.getAccounts();
            const account = accounts[0];
         /*   console.log(`account: ${account}`);
            console.log(`funding: ${address}`);
            console.log(`index: ${index}`);*/
            const contract = NewCrowFundingContract();
            contract.options.address = address;
            const result = await contract.methods.costRequest(index).send({
                from: account,
            });
            console.log('result :', result);

            resolve(result);
        } catch (e) {
            reject(e);
        }
    })
};
export {
    getFundingDetailArrayByTabId,
    createFunding,
    supportFunding,
    createRequest,
    getAllRequests,
    approveRequest,
    finalizeRequest
}